<?php
/**
 * @Author:      zk
 * @DateTime:    18-7-12 下午3:30
 * @Description: hrm 库 中 部门相关
 */
class HrmDepartment extends Eloquent
{
    protected $connection = 'mysql_hrm';
    
    protected $table = 'hr_department';
    
    /**
     * @Author:      zk
     * @DateTime:    18-7-19 下午2:29
     * @Description: 根据部门 父id 获取该部门下的所有部门
     * @param int $parent_id    部门父id
     */
    public static function getDepartmentByParentid($parent_id) {
        $select_arr = [
            'department_id', 'parent_id', 'name', 'description',
        ];
        $list = HrmDepartment::where('parent_id', $parent_id)
                ->select($select_arr)
                ->orderBy('department_id')
                ->get()
                ->toArray();
        
        $result = [];
        if(!empty($list)){
            foreach ($list as $k => $v) {
                //$temp = $v;
                $temp = [
                    'department_id' => ''.$v['department_id'],
                    'parent_id' => ''.$v['parent_id'],
                    'name' => $v['name'],
                    'description' => $v['description'],
                ];
                $res_child = self::getDepartmentByParentid($v['department_id']);
                if(!empty($res_child)){
                    $temp['child'] = $res_child;
                }
                $result[] = $temp;
            }
        }
        
        return $result;
    }
    
    /**
     * @Author:      zk
     * @DateTime:    18-7-19 下午2:53
     * @Description: 根据部门 父id 获取hrm平台下 该部门下的直接下级部门和直接人员
     * @param int $parent_id    部门父id
     */
    public static function getChildByParentid($parent_id) {
        //'name AS hr_user_name'    为了前端用户名显示一致， 臃余一下
        $select_arr = [
			'department_id', 'parent_id', 'name', 'name AS hr_user_name','description',
        ];
        $list = HrmDepartment::where('parent_id', $parent_id)
                ->select($select_arr)
                ->orderBy('department_id')
                ->get()
                ->toArray();
        $result = [];
        
        if(!empty($list)){
            $hrm_uaer_id_arr = OAUser::getAllUserid(2);     //OA系统中用户对应的hrm用户id
            foreach ($list as $k => $v) {
                $temp = $v;
                $next = [];
                $res_child = self::getChildByParentid($v['department_id']);
                if(!empty($res_child)){
                    $next = array_merge($res_child, $next);
                }
                //获取该部门下的直接人员
                $people = HrmUser::getUserInfoByDepartmentId($v['department_id'], $hrm_uaer_id_arr);
                if(!empty($people)){
                    $next = array_merge($people, $next);
                }
                $temp['next'] = $next;
                
                $result[] = $temp;
            }
        }
        
        return $result;
    }
    
    
}
